
#include <boost/foreach.hpp>

#include <xthread/guard.hpp>

#include "table_manager.hpp"

namespace xbase
{
	
	table::pointer table_manager::get_table(const std::string &p_tablename) const
	{
		Guard<ReadWriteLock::ReadLock> _guard(m_tables_lock.read_lock());
		table_map::const_iterator iter = m_tables.find(p_tablename);
		table::pointer _table; // default value
		if (iter != m_tables.end())
		{
			_table = iter->second;
		}
		return _table;
	}

	void table_manager::add_table(const table::pointer &p_table)
	{
		Guard<ReadWriteLock::WriteLock> _guard(m_tables_lock.write_lock());

		pair<table_map::iterator, bool>
			ret_val = m_tables.insert(table_map::value_type(p_table->table_name(),
									p_table));

		assert(ret_val.second == true); (void)ret_val;
		// if (ret_val.second == false)
		// {
		// 	// TODO: 
		// 	//LOG();
		// 	throw xbase::exception("table_manager::add_table");
		// }
	}

	// uint32_t table_manager::tablet_number() const
	// {
	// 	Guard<ReadWriteLock::ReadLock> _guard(m_tables_lock.read_lock());
	// 	uint32_t number = 0;
	// 	BOOST_FOREACH(const table_map::value_type &elem, m_tables)
	// 	{
	// 		number += elem.second->tablet_number();
	// 	}
	// 	return number;
	// }

	// uint32_t table_manager::memory_table_size() const
	// {
	// 	Guard<ReadWriteLock::ReadLock> _guard(m_tables_lock.read_lock());
	// 	uint32_t size = 0;
	// 	BOOST_FOREACH(const table_map::value_type &elem, m_tables)
	// 	{
	// 		size += elem.second->memory_table_size();
	// 	}
	// 	return size;
	// }

	void table_manager::get_stat(uint32_t &tablet_number,
				     uint32_t &memory_table_size) const {
		Guard<ReadWriteLock::ReadLock> _guard(m_tables_lock.read_lock());
		tablet_number = 0;
		memory_table_size = 0;
		BOOST_FOREACH(const table_map::value_type &elem, m_tables)
		{
			tablet_number += elem.second->tablet_number();
			memory_table_size += elem.second->memory_table_size();
		}
	}

} // namespace xbase
